package com.rms.hkpc.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.rms.hkpc.R;
import com.rms.hkpc.activity.base.BaseActivity;
import com.rms.hkpc.adapter.ImgBannerAdapter;
import com.rms.hkpc.adapter.RecordsRemarkAdapter;
import com.rms.hkpc.adapter.base.BaseAdapter;
import com.rms.hkpc.adapter.base.BasePagerAdapter;
import com.rms.hkpc.apiresult.ApiResultData;
import com.rms.hkpc.audio.AudioPresenter;
import com.rms.hkpc.audio.IAudioView;
import com.rms.hkpc.audio.RecordAudioImageView;
import com.rms.hkpc.audio.RecordVoicePopWindow;
import com.rms.hkpc.constant.AllConstants;
import com.rms.hkpc.control.LinearLayout;
import com.rms.hkpc.control.LinearLayoutManager;
import com.rms.hkpc.db.bean.DrawLineBean;
import com.rms.hkpc.db.bean.Event;
import com.rms.hkpc.db.dto.RecordsRemarksDto;
import com.rms.hkpc.db.dto.ShortDto;
import com.rms.hkpc.db.dto.WorkOrderPhotosDto;
import com.rms.hkpc.db.dto.WorksOrderDto;
import com.rms.hkpc.dialog.DeleteDialog;
import com.rms.hkpc.dialog.LoadingDialogUtils;
import com.rms.hkpc.dialog.ShortDialog;
import com.rms.hkpc.presenter.AddHocPresenter;
import com.rms.hkpc.util.DateUtil;
import com.rms.hkpc.util.DensityUtil;
import com.rms.hkpc.util.FileUtils;
import com.rms.hkpc.util.ImageUtil;
import com.rms.hkpc.util.OKHttpUtil;
import com.rms.hkpc.util.PermissionUtil;
import com.rms.hkpc.util.PhotoUtil;
import com.rms.hkpc.util.WindowUtil;
import com.rms.hkpc.view.IAddHocView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class AddHocActivity extends BaseActivity<IAddHocView, AddHocPresenter>
        implements IAddHocView, IAudioView.View {

    private final int ROTATE_ARG = 1;
    private final int WORD_ARG = 2;
    private final int DRAW_ARG = 3;
    private LinearLayout llIn;
    private RelativeLayout rlOut, rlCon;
    private ViewPager vpPic;
    private ArrayList<WorkOrderPhotosDto> list;
    private ImgBannerAdapter adapter;
    private EditText etInput;
    private boolean isAudio, isWord, isPlay;
    private AnimationDrawable mAnim;
    private IAudioView.Presenter audioPresenter;
    private RecordVoicePopWindow mRecordVoicePopWindow;
    private String id, statusId, audioFile, paramId, expAt, typeKey, wAt;
    private int result = 1, expDays, mPosition;
    private Integer val;
    private ImageView ivEdit, ivDraw, ivRecall, ivPlayAudio;
    private List<RecordsRemarksDto> listRemark;
    private RecordsRemarkAdapter adapterRemark;
    private Canvas canvas = null;
    private Paint mPaint = null;
    private float downX = 0, downY = 0, upX = 0, upY = 0;
    private Bitmap mBitmap;
    private TextView tvAddWord;
    private List<EditText> listEt;
    private RelativeLayout.LayoutParams lp;
    private DrawLineBean drawLineBean;
    // 保存画笔记录
    private List<Bitmap> listBitmap;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                hideLoading();
                Bitmap bitmap = (Bitmap) msg.obj;
                switch (msg.arg1) {
                    case ROTATE_ARG:
                        Matrix matrix = new Matrix();
                        matrix.setRotate(90);
                        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                        int pos = vpPic.getCurrentItem();
                        String newImgUrl = ImageUtil.getInstance().bitmapToUrl(AddHocActivity.this, newBitmap);
                        list.get(pos).setPhoto(newImgUrl);
                        adapter.notifyDataSetChanged();
                        vpPic.setAdapter(adapter);
                        vpPic.setCurrentItem(pos);
                        mPresenter.upload(newImgUrl, pos);
                        break;
                    case WORD_ARG:
                        initDrawWord(bitmap);
                        break;
                    case DRAW_ARG:
                        initDraw(bitmap);
                        break;
                }
            }
        }
    };

    private void initDrawWord(Bitmap bitmap) {
        initPaint();
        mBitmap = ImageUtil.getInstance().resizeBitmap(bitmap);
        ivDraw.setImageBitmap(mBitmap);
        canvas = new Canvas(mBitmap);
        listEt = new ArrayList<>();
        addEditText();
    }

    private void addEditText() {
        EditText et = (EditText) LayoutInflater.from(AddHocActivity.this).inflate(R.layout.et_add_img, null);
        et.setOnTouchListener(new MyOnTouchListener());
        et.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.border_red_bg, null));
            }
        });
        initLP();
        rlCon.addView(et, lp);
        et.requestFocus();
        WindowUtil.getInstance().showSoftInput(et);
        listEt.add(et);
    }

    private void initLP() {
        if (lp == null) {
            lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        }
    }


    private void initDraw(Bitmap bitmap) {
        initPaint();
        drawLineBean = new DrawLineBean();
        mBitmap = ImageUtil.getInstance().resizeBitmap(bitmap);
        listBitmap.clear();
        listBitmap.add(mBitmap.copy(Bitmap.Config.ARGB_8888, true));
        setBitmap(mBitmap);
    }

    private void setBitmap(Bitmap bitmap) {
        ivDraw.setImageBitmap(bitmap);
        canvas = new Canvas(bitmap);
        canvas.drawBitmap(bitmap, new Matrix(), mPaint);
    }

    private void initPaint() {
        if (mPaint == null) {
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Paint.Style.FILL);
            mPaint.setColor(Color.RED);
            mPaint.setTextSize(DensityUtil.px2sp(20));
            mPaint.setStrokeWidth(4);
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_hoc;
    }

    @Override
    protected void initView() {
        WindowUtil.getInstance().setBarBgColor(this, R.color.blue);
        llIn = fd(R.id.llIn);
        rlOut = fd(R.id.rlOut);
        rlCon = fd(R.id.rlCon);
        tvAddWord = fd(R.id.tvAddWord);
        ivDraw = fd(R.id.ivDraw);
        ivRecall = fd(R.id.ivRecall);
        vpPic = fd(R.id.vp_pic);
        ivPlayAudio = fd(R.id.iv_audio_play);
        list = new ArrayList<>();
        listBitmap = new ArrayList<>();
        adapter = new ImgBannerAdapter(this, this, list, R.layout.vp_img);
        adapter.setOnItemClickListener(new BasePagerAdapter.OnItemClickListener() {
            @Override
            public void onClickListener(View v, int position) {
                Intent intent = new Intent();
                intent.setClass(AddHocActivity.this, ImagePreviewActivity.class);
                intent.putExtra(AllConstants.WHAT, list);
                intent.putExtra(AllConstants.ID, position);
                startActivity(intent);
            }
        });
        adapter.setOnItemLongClickListener(new BasePagerAdapter.OnItemLongClickListener() {
            @Override
            public void onLongClickListener(View v, int position) {
                new DeleteDialog(AddHocActivity.this, new DeleteDialog.OnClickListener() {

                    @Override
                    public void okClick() {
                        list.remove(position);
                        adapter.notifyDataSetChanged();
                        vpPic.setAdapter(adapter);
                    }
                }).show();
            }
        });
        vpPic.setAdapter(adapter);
        ivEdit = fd(R.id.iv_edit);
        etInput = fd(R.id.et_input);
        etInput.setOnEditorActionListener(new MyOnEditorActionListener());
        OnClickListener onClickListener = new OnClickListener();
        ivRecall.setOnClickListener(onClickListener);
        ivEdit.setOnClickListener(onClickListener);
        fd(R.id.iv_audio_play).setOnClickListener(onClickListener);
        fd(R.id.iv_close).setOnClickListener(onClickListener);
        fd(R.id.iv_refresh).setOnClickListener(onClickListener);
        fd(R.id.tv_t).setOnClickListener(onClickListener);
        fd(R.id.iv_add).setOnClickListener(onClickListener);
        fd(R.id.iv_photo).setOnClickListener(onClickListener);
        fd(R.id.btn_title).setOnClickListener(onClickListener);
        fd(R.id.btn_status).setOnClickListener(onClickListener);
        fd(R.id.btn_other).setOnClickListener(onClickListener);
        fd(R.id.btn_save).setOnClickListener(onClickListener);
        fd(R.id.tvDrawDone).setOnClickListener(onClickListener);
        fd(R.id.ivRecall).setOnClickListener(onClickListener);
        fd(R.id.tvAddWord).setOnClickListener(onClickListener);
//        录音
        RecordAudioImageView ivAudio = fd(R.id.iv_audio);
        audioPresenter = new AudioPresenter<IAudioView.View>(this, this);
        audioPresenter.init();
        ivAudio.setOnVoiceIVCallBack(new MyOnVoiceIVCallBack());
        RecyclerView rvRemark = fd(R.id.rv_remark);
        rvRemark.setNestedScrollingEnabled(false);
        rvRemark.setItemAnimator(null);
        listRemark = new ArrayList<>();
        adapterRemark = new RecordsRemarkAdapter(this, listRemark, R.layout.rvitem_remark);
        adapterRemark.setOnItemLongClickListener(new BaseAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClickListener(View v, int position) {
                new DeleteDialog(AddHocActivity.this, new DeleteDialog.OnClickListener() {

                    @Override
                    public void okClick() {
                        listRemark.remove(position);
                        adapterRemark.notifyItemRemoved(position);
                        adapterRemark.notifyItemRangeChanged(position, adapterRemark.getItemCount() - position);
                    }
                }).show();
            }
        });
        rvRemark.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvRemark.setAdapter(adapterRemark);
        if (getIntent().getStringExtra(AllConstants.WHAT) != null) {
            id = getIntent().getStringExtra(AllConstants.WHAT);
            mPresenter.getRecords(id);
        }
    }

    class MyOnTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (v.getId() == R.id.ivDraw) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = event.getX();
                        downY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        upX = event.getX();
                        upY = event.getY();
                        canvas.drawLine(downX, downY, upX, upY, mPaint);
                        ivDraw.invalidate();
                        DrawLineBean.Line line = new DrawLineBean.Line(downX, downY, upX, upY);
                        drawLineBean.addLine(line);
                        downX = upX;
                        downY = upY;
                        break;
                    case MotionEvent.ACTION_UP:
                        upX = event.getX();
                        upY = event.getY();
                        canvas.drawLine(downX, downY, upX, upY, mPaint);
                        ivDraw.invalidate();
                        listBitmap.add(mBitmap.copy(Bitmap.Config.ARGB_8888, true));
                        break;
                }
            } else {
                WindowUtil.getInstance().hideSoftInput(v);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = event.getRawX();
                        downY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        v.setX(v.getX() + event.getRawX() - downX);
                        v.setY(v.getY() + event.getRawY() - downY);
                        downX = event.getRawX();
                        downY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        upX = event.getRawX();
                        upY = event.getRawY();
                        break;
                }
                if (upX - downX < 5 && upY - downY < 5) {
                    return false;
                } else {
                    if (!TextUtils.isEmpty(((EditText) v).getText().toString())) {
                        v.setBackground(null);
                    }
                    return true;
                }
            }
            return true;
        }
    }

    class MyOnEditorActionListener implements TextView.OnEditorActionListener {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                if (TextUtils.isEmpty(etInput.getText().toString())) {
                    Toast.makeText(AddHocActivity.this, R.string.empty_remark, Toast.LENGTH_LONG).show();
                    return false;
                }
                listRemark.add(0, new RecordsRemarksDto(id, id, etInput.getText().toString()));
                adapterRemark.notifyItemInserted(0);
                etInput.setText("");
                return true;
            }
            return false;
        }
    }

    class MyOnVoiceIVCallBack implements RecordAudioImageView.OnVoiceIVCallBack {

        @Override
        public void onStartRecord() {
            if (PermissionUtil.addPermission(AddHocActivity.this,
                    new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    AllConstants.RECORD_AUDIO)) {
                isAudio = true;
                audioPresenter.startRecord();
            }
        }

        @Override
        public void onStopRecord() {
            audioPresenter.stopRecord();
        }

        @Override
        public void onWillCancelRecord() {
            audioPresenter.willCancelRecord();
        }

        @Override
        public void onContinueRecord() {
            audioPresenter.continueRecord();
        }
    }

    @Override
    protected AddHocPresenter createPresenter() {
        return new AddHocPresenter();
    }

    @Override
    public List<RecordsRemarksDto> getRemarks() {
        if (!TextUtils.isEmpty(etInput.getText().toString())) {
            listRemark.add(new RecordsRemarksDto(id, id, etInput.getText().toString()));
        }
        return listRemark;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getStatusId() {
        return statusId;
    }

    @Override
    public String getParamId() {
        return paramId;
    }

    @Override
    public String getVoice() {
        return audioFile;
    }

    @Override
    public int getVal() {
        return val;
    }

    @Override
    public int getResult() {
        return result;
    }

    @Override
    public int getExpDays() {
        return expDays;
    }

    @Override
    public String getExpAt() {
        return expAt;
    }

    @Override
    public String getWAt() {
        return wAt;
    }

    @Override
    public List<WorkOrderPhotosDto> getPhotos() {
        return list;
    }

    @Override
    public void onGetDataSuccess(ApiResultData<WorksOrderDto> apiResult) {
        if (apiResult.getStatus() != 2000) {
            Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        WorksOrderDto data = apiResult.getData();
        // 狀態
        statusId = data.getStatus() == null ? "" : data.getStatus().getId();
        // 圖片組
        if (data.getPhotos() != null) {
            list.clear();
            list.addAll(data.getPhotos());
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setPhoto(OKHttpUtil.NET_URL + "/api/utils/images/400/" + list.get(i).getPhoto());
            }
            adapter.notifyDataSetChanged();
            vpPic.setAdapter(adapter);
        }
        // 備注
        if (data.getRemarks() != null && data.getRemarks().size() > 0) {
            listRemark.clear();
            listRemark.addAll(data.getRemarks());
            adapterRemark.notifyDataSetChanged();
        }
        paramId = data.getParam() == null ? "" : data.getParam().getId();
        val = data.getVal();
        result = data.getResult();
        expDays = data.getExpDays();
        expAt = DateUtil.getInstance().DateTimeToStr(data.getExpAt(), "yyyy-MM-dd HH:mm:ss");
        wAt = DateUtil.getInstance().DateTimeToStr(data.getwAt(), "yyyy-MM-dd HH:mm:ss");
        // 音频文件
        audioFile = data.getVoice() == null ? "" : data.getVoice();
    }

    @Override
    public void onGetDataFails(Exception msg) {
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onUploadSuccess(ApiResultData<String> apiResult, int pos) {
        if (apiResult.getStatus() != 2000) {
            Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        String result = apiResult.getData();
        if (isAudio) {
            audioFile = result;
        } else {
            list.get(pos).setPhoto(OKHttpUtil.IMG_URL + result);
        }
    }

    @Override
    public void onUploadFails(Exception msg, int pos) {
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
        if (!isAudio) {
            list.remove(pos);
            adapter.notifyDataSetChanged();
            vpPic.setAdapter(adapter);
        }
    }

    @Override
    public void onUpdateSuccess(ApiResultData<String> apiResult) {
        Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
        if (apiResult.getStatus() == 2000) {
            editFinish();
        }
    }

    @Override
    public void onUpdateFails(Exception msg) {
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onGetComboSuccess(ApiResultData<List<ShortDto>> apiResult) {
        if (apiResult.getStatus() != 2000) {
            Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        new ShortDialog(this, apiResult.getData(), R.string.p_sel, typeKey.equals("status") ? statusId : paramId,
                new ShortDialog.IChoiceListener() {
                    @Override
                    public void getChoiceFromDialog(ShortDto bean) {
                        if (typeKey.equals("status")) {
                            statusId = bean.getId();
                        } else {
                            paramId = bean.getId();
                        }

                    }
                }).show();
    }

    @Override
    public void onGetComboFails(Exception msg) {
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCreateSuccess(ApiResultData<String> apiResult) {
        Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
        if (apiResult.getStatus() == 2000) {
            editFinish();
        }
    }

    @Override
    public void onCreateFails(Exception msg) {
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void showNormalTipView() {
        if (popIsNull()) {
            mRecordVoicePopWindow = new RecordVoicePopWindow(this);
        }
        mRecordVoicePopWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    @Override
    public void showTimeOutTipView(int remainder) {
        if (!popIsNull()) {
            mRecordVoicePopWindow.showTimeOutTipView(remainder);
        }
    }

    @Override
    public void showRecordingTipView() {
        if (!popIsNull()) {
            mRecordVoicePopWindow.showRecordingTipView();
        }
    }

    @Override
    public void showRecordTooShortTipView() {
        if (!popIsNull()) {
            mRecordVoicePopWindow.showRecordTooShortTipView();
        }
    }

    @Override
    public void showCancelTipView() {
        if (!popIsNull()) {
            mRecordVoicePopWindow.showCancelTipView();
        }
    }

    @Override
    public void hideTipView() {
        if (!popIsNull()) {
            mRecordVoicePopWindow.dismiss();
        }
    }

    @Override
    public void updateCurrentVolume(int db) {
        if (!popIsNull()) {
            mRecordVoicePopWindow.updateCurrentVolume(db);
        }
    }

    @Override
    public void finishRecord(String file) {
        mPresenter.upload(file, 0);
    }

    @Override
    public void finishPlayAudio() {
        isPlay = false;
        ivPlayAudio.setBackgroundResource(R.drawable.ic_audio);
        if (mAnim != null) {
            mAnim.stop();
            mAnim = null;
        }
        Log.i(AllConstants.TAG, "finishPlayAudio");
    }

    private boolean popIsNull() {
        return mRecordVoicePopWindow == null;
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(final View v) {
            switch (v.getId()) {
                // 选择状态
                case R.id.btn_status:
                    typeKey = "status";
                    mPresenter.combo(typeKey);
                    break;
                // 选择标题
                case R.id.btn_title:
                    typeKey = "espparams";
                    mPresenter.combo(typeKey);
                    break;
                // 保存
                case R.id.btn_save:
                    if (TextUtils.isEmpty(statusId)) {
                        Toast.makeText(AddHocActivity.this, R.string.empty_status, Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (TextUtils.isEmpty(paramId)) {
                        Toast.makeText(AddHocActivity.this, R.string.empty_params, Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (TextUtils.isEmpty(wAt)) {
                        Toast.makeText(AddHocActivity.this,R.string.p_sel_time_other,Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(id)) {
                        mPresenter.create();
                    } else {
                        mPresenter.update();
                    }
                    break;
                // 其它
                case R.id.btn_other:
                    Intent intent = new Intent();
                    intent.setClass(AddHocActivity.this, AddHocOtherActivity.class);
                    intent.putExtra(AllConstants.RESULT, result);
                    intent.putExtra(AllConstants.VALUE, val);
                    intent.putExtra(AllConstants.EXP, expAt);
                    intent.putExtra(AllConstants.WAT, wAt);
                    startActivityForResult(intent, 4);
                    break;
                // 调用相机
                case R.id.iv_photo:
                    PhotoUtil.getInstance().toCamera(AddHocActivity.this);
                    break;
                // 调用相册
                case R.id.iv_add:
                    PhotoUtil.getInstance().toGallery(AddHocActivity.this);
                    break;
                // 旋转图片
                case R.id.iv_refresh:
                    if (list.size() > 0) {
                        showLoading();
                        ImageUtil.getInstance().getBitmap(AddHocActivity.this, list.get(vpPic.getCurrentItem()).getPhoto(), handler, ROTATE_ARG);
                    } else {
                        Toast.makeText(AddHocActivity.this, R.string.p_add_pic, Toast.LENGTH_SHORT).show();
                    }
                    break;
                // 图片添加文字
                case R.id.tv_t:
                    if (list.size() > 0) {
                        showLoading();
                        isWord = true;
                        mPosition = vpPic.getCurrentItem();
                        rlOut.setVisibility(View.VISIBLE);
                        ivRecall.setVisibility(View.GONE);
                        ivDraw.setOnTouchListener(null);
                        ivDraw.setOnClickListener(new OnClickListener());
                        tvAddWord.setVisibility(View.VISIBLE);
                        llIn.setChildClickable(false);
                        ImageUtil.getInstance().getBitmap(AddHocActivity.this, list.get(mPosition).getPhoto(), handler, WORD_ARG);
                    } else {
                        Toast.makeText(AddHocActivity.this, R.string.p_add_pic, Toast.LENGTH_SHORT).show();
                    }
                    break;
                // 圖片添加文字的添加輸入框
                case R.id.tvAddWord:
                    addEditText();
                    break;
                // 绘画图片
                case R.id.iv_edit:
                    if (list.size() > 0) {
                        showLoading();
                        isWord = false;
                        mPosition = vpPic.getCurrentItem();
                        rlOut.setVisibility(View.VISIBLE);
                        ivRecall.setVisibility(View.VISIBLE);
                        llIn.setChildClickable(false);
                        ivDraw.setOnClickListener(null);
                        ivDraw.setOnTouchListener(new MyOnTouchListener());
                        tvAddWord.setVisibility(View.GONE);
                        ImageUtil.getInstance().getBitmap(AddHocActivity.this, list.get(mPosition).getPhoto(), handler, DRAW_ARG);
                    } else {
                        Toast.makeText(AddHocActivity.this, R.string.p_add_pic, Toast.LENGTH_SHORT).show();
                    }
                    break;
                // 編輯展示的圖片
                case R.id.ivDraw:
                    if (listEt != null && listEt.size() > 0) {
                        for (int i = 0; i < listEt.size(); i++) {
                            if (TextUtils.isEmpty(listEt.get(i).getText().toString().trim())) {
                                rlCon.removeView(listEt.get(i));
                                listEt.remove(i);
                                i--;
                            } else {
                                listEt.get(i).setBackground(null);
                            }
                        }
                    }
                    break;
                // 編輯圖片完成
                case R.id.tvDrawDone:
                    doneDraw();
                    break;
                // 撤回绘画圖片
                case R.id.ivRecall:
                    if (listBitmap.size() > 1) {
                        listBitmap.remove(listBitmap.size() - 1);
                        mBitmap = listBitmap.get(listBitmap.size() - 1).copy(Bitmap.Config.ARGB_8888, true);
                        drawLineBean = new DrawLineBean();
                        canvas = new Canvas(mBitmap);
                        canvas.drawBitmap(mBitmap, new Matrix(), mPaint);
                        ivDraw.setImageBitmap(mBitmap);
                    }
                    break;
                // 播放录音
                case R.id.iv_audio_play:
                    if (TextUtils.isEmpty(audioFile)) {
                        Toast.makeText(AddHocActivity.this, R.string.no_audio, Toast.LENGTH_LONG).show();
                    } else {
                        if (isPlay) {
                            audioPresenter.stopPlayRecord();
                        } else {
                            ivPlayAudio.setBackgroundResource(R.drawable.anim_play_voice);
                            mAnim = (AnimationDrawable) ivPlayAudio.getBackground();
                            mAnim.start();
                            audioPresenter.startPlayRecord(OKHttpUtil.VIDEO_URL + audioFile);
                            isPlay = true;
                        }
                    }
                    break;
                // 关闭
                case R.id.iv_close:
                    finish();
                    break;
            }
        }
    }

    private void doneDraw() {
        if (mBitmap != null) {
            if (isWord) {
                if (listEt.size() > 0) {
                    for (int i = 1; i < rlCon.getChildCount(); i++) {
                        drawText((EditText) rlCon.getChildAt(i));
                        rlCon.removeViewAt(i);
                    }
                    changeImage();
                    listEt.clear();
                }
            } else {
                changeImage();
            }
        }
        rlOut.setVisibility(View.GONE);
        llIn.setChildClickable(true);
    }

    private void drawText(EditText et) {
        canvas.drawText(et.getText().toString(), et.getX() + DensityUtil.dp2px(6), et.getY() + (et.getHeight() / 2.0f) + DensityUtil.dp2px(6), mPaint);
    }

    private void changeImage() {
        String newImgUrl = ImageUtil.getInstance().bitmapToUrl(AddHocActivity.this, mBitmap);
        list.get(mPosition).setPhoto(newImgUrl);
        adapter.notifyDataSetChanged();
        vpPic.setAdapter(adapter);
        vpPic.setCurrentItem(mPosition);
        mPresenter.upload(newImgUrl, mPosition);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 0) {
            if (requestCode == AllConstants.PIC_CAMERA) {
                Bitmap bitmap = PhotoUtil.getInstance().rotatingPic(PhotoUtil.getInstance().getAngle(), BitmapFactory.decodeFile(PhotoUtil.getInstance().imgUrl));
                showLocalPic(ImageUtil.getInstance().bitmapToUrl(this, bitmap));
            } else if (requestCode == AllConstants.PIC_GALLERY) {
                showLocalPic(FileUtils.getFilePathByUri(this, data.getData()));
            } else if (requestCode == 4 && resultCode == 1) {
                if (data != null) {
                    val = data.getIntExtra(AllConstants.VALUE, 0);
                    result = data.getIntExtra(AllConstants.RESULT, 1);
                    expAt = data.getStringExtra(AllConstants.EXP);
                    wAt = data.getStringExtra(AllConstants.WAT);
                }
            }
        }
    }

    private void showLocalPic(String imgUrl) {
        String url = ImageUtil.getInstance().bitmapToUrl(this, ImageUtil.getInstance().resizeImage(imgUrl));
        list.add(new WorkOrderPhotosDto(id, url));
        adapter.notifyDataSetChanged();
        vpPic.setAdapter(adapter);
        int pos = list.size() - 1;
        vpPic.setCurrentItem(pos);
        mPresenter.upload(url, pos);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PermissionUtil.requestPermission(grantResults)) {
            if (requestCode == AllConstants.PIC_CAMERA) {
                PhotoUtil.getInstance().toCamera(this);
            } else if (requestCode == AllConstants.PIC_GALLERY) {
                PhotoUtil.getInstance().toGallery(this);
            }
        }
    }

    private void editFinish() {
        EventBus.getDefault().post(new Event(300));
        finish();
    }

    @Override
    public void onBackPressed() {
        if (rlOut.getVisibility() == View.VISIBLE) {
            rlOut.setVisibility(View.GONE);
            llIn.setChildClickable(true);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        audioPresenter.stopPlayRecord();
    }
}